<template>
<div style="height: 100%;">
  <div class="payList">
    <ul class="white_bg">
      <li>
        <span class="right">{{orderInfo.amt}}元</span> 消费总金额
      </li>
      <li>
        <span class="right">{{orderInfo.noSlae}}元</span> 不参与优惠金额
      </li>
      <li>
        <span class="right">{{orderInfo.deskNum}}</span> 桌号
      </li>
    </ul>
  </div>
  <div class="payCenter" v-if="hasCoupon">
    <div class="payTit">
      可以使用的优惠券
    </div>
    <use-coupon v-for="(item, index) in myCoupons" :key="index" :item="item" :num="index" @checkedCoupon="checkedCoupon"></use-coupon>
  </div>
  <!--卡包无此订单的优惠券-->
  <template v-if="!hasCoupon">
    <!--商户优惠信息-->
    <div class='mactActively' v-if="!recomCou">
        <div class="tagtitle" v-if="!noAct"><img src="../../images/MactActively_02.png" /></div>
        <div class="activeTit" v-if="!noAct">活动说明</div>
        <div class='activeItem' v-for="couponItem in activityList">
            <div class="coupon_act_coupon">
              <div class="tagImage"><img src="../../images/MactActively.png" /></div>
                <div class="couponDiv">
									<coupon-denomination :item="couponItem.coupon"></coupon-denomination>
								</div>
                <div class="card_info_actively">
                  <div class="card_infoup">
                    <p class="card_name">{{couponItem.act.actName}}</p>
                    <span class="card_price">面值：{{couponItem.coupon.denomination | denomination(couponItem.coupon.couponType || couponItem.coupon.type)}}</span>
                  </div>
                    <p class="activeDes white_bg">{{couponItem.act.actDsc}}</p>
                </div>
            </div>
        </div>
        <div class="noAct" v-if="noAct">此商户没有相关活动</div>
    </div>
    <!--推荐优惠券-->
    <div class="buyCoupon" v-if="recomCou">
        <div class="buyCouponTit">为你推荐优惠券</div>
        <coupon-card :coupon="coupon" v-for="(coupon,index) in recomCouList" :key='index' view="coupon" :orderId="orderId" @exchange="exchange"></coupon-card>
    </div>
  </template>

  <div class="payBtn" :class="{payBtnBg: !checked}">
    <div class="payEvent" :class="{'disabledBtn':payDisable}" @click="payEvent">{{orderInfo|orderState}}</div>
    <div @click="payDetailE">
      <icon icon-name="#icon-qiabaomaidan-"></icon>
      <div class="payInfo">
        <p class="payMoney">{{payNum | formatMoney}}元</p>
        <p class="payCoupon" v-if="checked">使用优惠券</p>
      </div>
    </div>
  </div>

  <!-- 购买弹框-->
  <exchange-box v-if="exchageShow" :param="couParams" :exchageShow="exchageShow" @hiddenExc="exchageShow=false" @goOnPay="goOnPay"></exchange-box>


</div>
</template>
<script>
import exchangeBox from 'src/componentes/global/exchangeBox.vue'
import UseCoupon from './coupon.vue'
import couponNum from '../../componentes/global/couponNum.vue'
import star from '../../componentes/global/star.vue'
import getData from '../../service/getData.js'
import getData2 from '../../service/getData2.js'
import * as types from '../../vuex/types.js'
import {Storage} from 'src/utils/storage.js'

import {
  mapState
} from 'vuex'
import {
  Toast,
  Indicator,
  MessageBox
} from 'mint-ui'
export default {
  data: function() {
    return {
      activityList: [],
      // showActList: true,
      noAct: true,
      select: false,
      slideLeft: false,
      myCoupons: [], // 推送我卡包里的电子券
      storeC: [],
      couponCount: 0,
      hasCoupon: false, //是否拥有代金券
      orderInfo: {},
      recommInfo: {},
      recomCouList: [], // 为你推荐电子券数量
      payDetail: false,
      payNum: 0,
      payDisable: false, //禁止按钮
      recomCou: true,
      exchageShow: false, // 立即兑换弹框
      couParams: {},
      // shareInfo:false,
      // usrAmt:0,
      checked: false, // 可以使用的优惠券里 被选中的
      coupon: '', // 被选中的电子券
      payUrl: '', // 跳到第三方支付链接
      lookState:false,
      orderId:this.$route.query.o
    }
  },
  components: {
    exchangeBox,
    couponNum,
    star,
    // cardImg,
    // RewardModal,
    UseCoupon
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo,
      couponPay: state => state.pay.couponPay,
      couponInfo: state => state.coupon.couponInfo, //优惠券数组
    })
  },
  watch: {
    couponPay() {
      let me = this;
      if (this.couponPay) {
        this.getOrderInfo();
      }
      this.$store.commit("coupon_pay", false);
    }
  },
  methods: {
    //计算（参与活动）优惠后的价格
    computeAm(coupon) { // discounts
      let am = (this.orderInfo.amt * 1000 - this.orderInfo.noSlae * 1000) / 1000;
      if (coupon.type == 'rebate') { //折扣券
        // 打折后金额 * 100 分为单位
        am = (((this.orderInfo.amt * 100 -  this.orderInfo.noSlae * 100) * coupon.denomination / 100 + this.orderInfo.noSlae * 100) / 100).toFixed(2)
      } else {
        am = (parseInt(am * 1000) - coupon.denomination * 1000) / 1000 + this.orderInfo.noSlae
      }
      return am;
    },
    //获取订单信息
    getOrderInfo() {
      let me = this;
      if (this.userInfo.usrId) {
        getData.getOrder({
          method: 'post',
          data: {
            orderId: me.$route.query.o, //100000501507874309750/me.$route.query.o
            usrId: me.userInfo.usrId,
            mchtId: me.$route.query.m //me.$route.query.m
          }
        }).then(rep => {
          if (rep.respCode == '00') {
            // 判断订单状态
            if (rep.content.order.orderState == 'payed') {
              me.payDisable = true;
              me.lookState=true
              me.$router.push({
                "name": "paySuccess"
              });
              return;
            }
            if (rep.content) {
              me.orderInfo = rep.content.order;
              me.payNum = rep.content.order.amt;
              // 推荐我卡包里的电子券
              me.bestCoupon({
                orderId: me.orderInfo.orderId,
                mchtId: me.orderInfo.mchtId
              });
              //获取用户芸券数量
              me.recommInfo.amt = rep.content.order.amt;
              if (me.orderInfo.noSlae >= 0) {
                me.recommInfo.noSlae = parseInt(me.orderInfo.noSlae)
              } else {
                me.recommInfo.noSlae = '0'
              }
              if (me.userInfo.yunNum) {
                me.recommInfo.mchtId = rep.content.order.mchtId;
                me.recommInfo.yunNum = me.userInfo.yunNum;
                me.recommInfo.usrId = me.userInfo.usrId;
              } else {
                me.getYunNum();
              }
            }
          } else if (rep.respCode == '4111' || rep.respCode == '4222') {
          	me.lookState=true
            MessageBox.alert(rep.errorInfo).then(action => {
              me.$router.push({path: '/home'})
            });
          } else {
            Toast({
              message: rep.errorInfo,
              duration: 1000
            });
          }
        });
      } else {
        Toast({
          message: '还没有登录',
          duration: 800
        });
      }
    },
    getActList() {
      // 商户活动信息
      getData2.getPillActivity({
        method: 'post',
        data: {
          "aoData": "",
          "mchtId": this.orderInfo.mchtId,
          "money": this.payNum,
          "type": "pay"
        }
      }).then(rep => {
        if (rep.respCode = '00') {
          this.activityList = rep.content.list;
          if ((rep.content.list) && !(rep.content.list.length==0)) {
            this.noAct = false;
          }
        }
      });
    },
    getRecomCou() {
      let data = {
        method: 'post',
        data: {
          amt: this.orderInfo.amt,
          mchtId: this.orderInfo.mchtId,
          noSlae: this.orderInfo.noSlae, // 无优惠金额
          page: 1,
          rows: 9999,
          usrId: this.userInfo.usrId,
          yunNum: this.orderInfo.yunNum
        }
      }
      let that = this
      getData.recommendCoupon(data).then(rep => {
        if (rep.respCode === '00') {
          let list = rep.content.couponList || []
          if (list.length === 0 || !rep.content.couponList||that.orderInfo.amt==that.orderInfo.noSlae) {
            this.recomCou = false
            this.getActList(this.orderInfo)
          } else {
            list.forEach(item => {
              item.type = item.couponType
              item.name = item.couponName
              item.comNum = item.couponComNum
            })
            that.recomCouList = list
          }
        }
      })
    },
    //获取芸券值(推荐电子券时用)
    getYunNum: function() {
      let me = this;
      getData.myAccount({}, me.userInfo.usrId).then(function(rep) {
        if (rep.respCode == '00') {
          me.recommInfo.mchtId = me.orderInfo.mchtId.toString();
          me.recommInfo.yunNum = rep.content;
          me.recommInfo.usrId = me.userInfo.usrId;
          // me.showActList = false;
        }
      })
    },
    bridgeReady(data, orderId, params) {
      let that = this
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest', data,
        function(res){
          if(res.err_msg == "get_brand_wcpay_request:ok" ) {  // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
            // Indicator.open('正在确认订单中...')
            that.$store.commit('changeState', true)
            getData.payState(params).then(res => {
              if (res.respCode === '00') {
              	that.lookState=true
                that.$router.push({
                  name: 'paySuccess',
                  query: {orderId}
                })
              } else {
                Toast({
                  message: res.errorInfo,
                  duration: 1000
                });
              }
            })
          } else if(res.err_msg == "get_brand_wcpay_request:cancel" ) {
            Toast({
              message: '支付已取消',
              duration: 1000
            });
          } else if(res.err_msg == "get_brand_wcpay_request:fail" ) {
            Toast({
              message: '支付失败',
              duration: 1000
            });
          }
        }
      );
    },
    //生成支付
    payEvent: async function() {
      this.$store.commit('changeState', true)
      if (!this.orderInfo.mchtId) {return}
      if (this.payDisable) {return}
      let me = this
      let couponId = ''
      let couponNo = ''
      let denomination = ''
      let type
      if (this.coupon.isChecked) {
        type =  this.coupon.type
        couponId = this.coupon.couponId
        couponNo = this.coupon.couNo.split(',')[0]
        denomination = this.coupon.denomination
      }
      let params = {
        method: 'post',
        data: {
          num: couponNo ? 1 : 0, // 使用电子券张数
          coupons: couponNo?`${couponId}+${couponNo}`:'', // 电子劵id, 券码（id + 券码 + 券码, id + 券码 + 券码）
          couponAmt: ((me.orderInfo.amt * 100 - me.payNum * 100) / 100).toFixed(2), // 电子券优惠金额
          usrId: me.userInfo.usrId,
          mchtId: me.orderInfo.mchtId, // 商户号
          orderId: me.orderInfo.orderId, // 订单号
          openId: me.userInfo.usrWchatOpenid, // 微信openId
          payNum: (Number(me.payNum)).toFixed(2)
        }
      }
      let rep = await getData.payLink(params)
      if (rep.respCode == '00') {
        //支付订单存到sessionStorage
        Storage.set("hasPayOrder", {
          type,
          num: 1,
          couponId,
          couponNo,
          denomination,
          couponNoInfo: me.coupon,
          usrId: me.userInfo.usrId,
          mchtId: me.orderInfo.mchtId,
          orderId: me.orderInfo.orderId,
          couponAmt: ((me.orderInfo.amt * 100 - me.payNum * 100) / 100).toFixed(2),
          payNum: (Number(me.payNum)).toFixed(2),
          market: rep.content.market, //奖励金
          market2:rep.content.settUsrAmt
        });
        if (Number(me.payNum) !== 0) {
          // let data = JSON.parse(rep.content.data)
          // 调用微信支付接口
          // me.bridgeReady(data, me.orderInfo.orderId, params)
          // if (rep.content.market) {
          //   this.usrAmt = rep.content.market;
          //   this.shareInfo = true;
          //   this.payUrl = rep.content.payUrl || rep.content.data // 跳转到第三方支付
          //   return
          // }
          let url = rep.content.payUrl || rep.content.data
          location.href = url
        } else {
          me.lookState=true
          me.$router.replace({
              name: 'paySuccess',
              query: {orderId: me.orderInfo.orderId}
          })
        }
      } else {
        Toast({
          message: rep.errorInfo,
          duration: 1000
        });
      }
    },
    //查看使用电子券详情
    payDetailE() {
      this.payDetail = this.payDetail ? false : true;
    },
    //我卡包里的电子券
    bestCoupon(param) {
      let me = this
      let data = {
        mchtId: param.mchtId,
        amt:this.orderInfo.amt,
        orderAmount: this.orderInfo.amt - this.orderInfo.noSlae,
        usrId: this.userInfo.usrId,
        amt: this.orderInfo.amt
      }
      getData.optionalCoupons({
         method: 'post',
         data
      }, me.userInfo.usrId).then(rep => {
        let data = rep.content.couponList;
        if (data.length === 0) {
          // 为你推荐优惠券
          me.hasCoupon = false
          this.getRecomCou()
          return
        }
        data.forEach(item => {
          item.isChecked = false
        })
        me.hasCoupon = true
        me.myCoupons = data
      })
    },
    checkedCoupon(index, coupon) {
    	if (coupon.couNo == '') {
    		  Toast({
          message: "该电子券在'我的订单'已绑定，如果使用请提前取消订单",
          duration: 1000
        });
    		return
    	}
      if (!this.myCoupons[index].isChecked) {
        this.myCoupons.forEach(item => {
          item.isChecked = false
        })
        this.myCoupons[index].isChecked = !this.myCoupons[index].isChecked
        this.checked = true
        this.payNum = this.computeAm(coupon)
        this.coupon = coupon
      } else {
        this.myCoupons[index].isChecked = !this.myCoupons[index].isChecked
        this.checked = this.myCoupons[index].isChecked
        if (this.myCoupons[index].isChecked) {
          this.payNum = this.computeAm(coupon)
          this.coupon = coupon
        } else {
          this.payNum = this.orderInfo.amt
          this.coupon = []
        }
      }
    },
    //跳转详情
    goCouponDetl(params) {
      var me = this;
      me.lookState=true
      Storage.set("couponInfo", params);
      // this.$router.push({name:'couponDetail',query:{type:'noExchange'}});
      this.$router.push({
        name: 'couDetail',
        query: {
          type: 'noExchange',
          couponId: params.couponId,
          mchtId: params.mchtId,
          seq: params.seqNo || '',
          usrId: '',
          usrPicId: ''
        }
      });
    },
    exchange(params) {
      this.exchageShow = true
      this.couParams = params
    },
    goOnPay() {  // 隐藏弹框
      this.exchageShow = false
      this.bestCoupon({
        orderId: this.orderInfo.orderId,
        mchtId: this.orderInfo.mchtId
      });
    }
  },
  created: function() {
    //获取订单信息
    this.getOrderInfo();
  },
  mounted: async function(){
    //关闭“订单查询中...”提示
          let me=this
    this.$nextTick(() => {
    });
  },
}
</script>
<style scoped>
.payList li {
  border-bottom: 1px solid #f0f0f0;
  height: 3rem;
  line-height: 3rem;
  color: #666;
  padding: 0 .667rem;
  /*background: #fff;*/
  box-sizing: border-box;
  position: relative;
}

.payList li:last-child {
  border: none;
}

.payList li span {
  color: #333;
}




/*center*/

.payCenter {
  background: linear-gradient(35deg, #ec4e8a, #f95a7c);
  min-height: -webkit-calc(100% - 10rem);
  padding-bottom: 4rem;
}

.payTit {
  height: 3rem;
  line-height: 3rem;
  padding: 0 .667rem;
  color: #fff;
}

.grayTxt .pay_coupon_num,
.grayTxt .icon-jianshao- {
  color: #999;
}




/*电子券推荐*/

.buyCoupon {
  padding-bottom: 4.6rem;
}

.buyCouponTit {
  color: #333;
  height: 3rem;
  line-height: 3rem;
  padding: 0 .667rem;
  border-top: 1px solid #f0f0f0;
}




/*订单使用电子券详细*/

.payShaw {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 4rem;
  background: rgba(0, 0, 0, .6);
  z-index: 99;
}

.payDetail {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  min-height: 10rem;
  /*background: #fff;*/
}

.payDetailT {
  height: 3rem;
  line-height: 3rem;
  padding: 0 .667rem;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
  font-weight: bold;
}

.payDetailT2 {
  height: 3rem;
  line-height: 3rem;
  padding: 0 .667rem;
  border-bottom: 1px solid #f0f0f0;
  color: #666;
  font-size: 1rem;
}

.hasUseCou li {
  padding: .667rem;
  border-bottom: 1px solid #f0f0f0;
  overflow: hidden;
}

.hasUseCouC {
  flex: 1;
  padding: 0 0 0 .667rem;
  overflow: hidden;
}

.hasUseCouCT {
  display: block;
  color: #333;
  font-weight: bold;
  padding-top: .2rem;
}

.zhangshu {
  font-size: 1rem;
  color: #666;
  padding-top: .6rem;
  display: block;
}

.hasUseCouR {
  float: right;
  width: 5rem;
  display: flex;
  align-items: center;
  height: 4.2rem;
  justify-content: space-between;
}

.hasUseCouR .iconfont {
  color: #ec4e8a;
  font-size: 1.2rem;
  font-weight: bold;
}




/*按鈕*/

.payBtn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 4rem;
  background: #ffffff;
  box-shadow: 0 -.2rem 1rem rgba(0, 0, 0, .4);
  z-index: 99;
}

.payBtnBg {
  background: #333;
}

.payBtnBg .payMoney {
  color: #ec4e8a;
}

.payBtnBg .payCoupon {
  color: #939393;
}

.payBtn .icon {
  font-size: 2.8rem;
  float: left;
  margin: .6rem 0 0 .667rem;
}

.payInfo {
  float: left;
  line-height: 1.2rem;
  margin: .9rem 0 0 .6rem;
}

.payMoney {
  font-size: 1.2rem;
}

.payCoupon {
  font-size: .8rem;
}

.payEvent {
  float: right;
  height: 2.6rem;
  margin: .7rem .667rem 0 0;
  line-height: 2.6rem;
  background: linear-gradient(35deg, #ec4e8a, #f95a7c);
  padding: 0 2rem;
  font-size: 1.1rem;
  color: #fff;
  border-radius: .2rem;
}

.disabledBtn {
  background: #aaa;
}



/*商户活动*/

.coupon_act_coupon {
  position: relative;
  overflow: hidden;
  padding: 1rem 0.667rem;
  height: 8rem;
  margin-top: 0.667rem;
  box-sizing: border-box;
  background-size: 100%;
  background-color: #fff;
  border-bottom:1px solid #f0f0f0;
}
.coupon_act_coupon:first-child{
  margin-top:0;
}

.activeDes {
  font-size: 0.8rem;
  color: #999;
  /*background: #fff;*/
  margin-top:.4rem;
}

.activeTit {
  font-size: 1.2rem;
  font-weight: bold;
  margin-top:.667rem;
  padding-top: 1rem;
  padding-bottom:.667rem;
  padding-left: 0.667rem;
  color: #333;
  background:#fff;
  border-bottom:1px solid #f0f0f0;
}

.noAct {
  height: 8rem;
  font-size: 1rem;
  line-height: 8rem;
  color: #666;
  text-align: center;
}

.card_price {
  color: #666;
  line-height:1.5rem;
}
.tagImage{
  position:absolute;
  left:.5rem;
  top:1.4rem;
  z-index:9;
}
.tagImage img{
  width:2rem;
  height:1.9rem;
}
.mactActively{
  position:relative;
}
.tagtitle{
  position:absolute;
  right:1.068rem;
  top:-.4rem;
  z-index:20;
}
.tagtitle img{
  width:5.2rem;
  height:5.2rem;
}
  .card_info_actively{
    overflow: hidden;
    line-height:1.86rem;
    padding:0 .667rem
  }
  .card_infoup{border-bottom:1px dashed #f0f0f0;padding-bottom:.4rem;}
</style>
